import requests
import json
import os
import time
#cron: 9 8,22 * * *
#new Env("油价查询")

print("="*50)
print("⛽ 油价查询脚本开始执行 🚀")
print("="*50)

# 油价数据存储目录
OIL_DATA_DIR = "oil_data"

# 获取环境变量中的省份设置
PROVINCES = os.environ.get('OIL_PROVINCES', '广东').split('\n')
print(f"📋 查询省份列表: {PROVINCES}")

# 确保数据目录存在
if not os.path.exists(OIL_DATA_DIR):
    os.makedirs(OIL_DATA_DIR)
    print(f"✅ 创建数据目录: {OIL_DATA_DIR}")

# 计算涨跌幅度的函数
def get_price_change(current, last, oil_type, oil_name):
    result = {
        "current_price": current[oil_type],
        "last_price": last[oil_type] if last and oil_type in last else "无记录",
        "change": "",
        "symbol": "",
        "emoji": ""
    }
    
    if not last or oil_type not in last:
        print(f"  {oil_name}: 📊 无历史数据")
        return result
    
    try:
        current_price = float(current[oil_type])
        last_price = float(last[oil_type])
        change = current_price - last_price
        
        if change > 0:
            result["change"] = f"+{change:.2f}"
            result["symbol"] = "↑"
            result["emoji"] = "🔴"  # 上涨用红色
        elif change < 0:
            result["change"] = f"{change:.2f}"
            result["symbol"] = "↓"
            result["emoji"] = "🟢"  # 下跌用绿色
        else:
            result["change"] = "0.00"
            result["symbol"] = "→"
            result["emoji"] = "🟡"  # 持平用黄色
            
        print(f"  {oil_name}: 当前 {current_price} vs 历史 {last_price} → 变化 {result['emoji']}{result['symbol']}{abs(change):.2f}")
        
    except Exception as e:
        print(f"❌ 计算{oil_name}价格变化时出错: {str(e)}")
    
    return result

# 推送通知到企业微信机器人的函数
def send_wechat_message(message, province):
    print(f"\n📤 [推送] 发送 {province} 油价通知到企业微信...")
    url_wechat = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4ed66c7-ea68-4b51-be3f-8319beb4504d"
    print(f"🌐 企业微信URL: {url_wechat}")

    headers = {"Content-Type": "application/json"}
    data_wechat = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }

    try:
        response_wechat = requests.post(url_wechat, json=data_wechat, headers=headers)
        response_wechat.raise_for_status()
        result = response_wechat.json()
        
        if result["errcode"] == 0:
            print(f"✅ {province} 推送成功！")
        else:
            print(f"❌ {province} 推送失败: {result.get('errmsg', '未知错误')}")
        
        print(f"📨 {province} 企业微信响应:", json.dumps(result, indent=2))
        return True
        
    except Exception as e:
        print(f"❌ {province} 推送过程中发生错误: {str(e)}")
        return False

# 处理每个省份的油价查询并分别发送通知
success_count = 0
fail_count = 0

for province in PROVINCES:
    if not province.strip():  # 跳过空行
        continue
        
    province = province.strip()
    print(f"\n{'='*30}")
    print(f"🏢 处理省份: {province}")
    print(f"{'='*30}")
    
    # 根据省份生成数据文件路径
    DATA_FILE = os.path.join(OIL_DATA_DIR, f"oil_price_{province}.json")
    print(f"💾 数据存储文件: {DATA_FILE}")

    # 请求API获取数据
    print(f"\n[步骤1] 🌐 正在请求 {province} 油价API...")
    url = f"https://apis.tianapi.com/oilprice/index?key=81f94231ec7fabb001789aa365fb8d20&prov={province}"
    print(f"🔗 API请求URL: {url}")

    try:
        response = requests.get(url)
        response.raise_for_status()
        api_data = response.json()
        print("📊 API响应状态:", api_data.get("code", "未知"))
        print("💬 API返回消息:", api_data.get("msg", "未知"))
        
        if api_data["code"] != 200:
            print(f"❌ {province} API请求失败，跳过该省份")
            # 发送失败通知
            fail_message = f"❌ {province}油价查询失败\n错误信息: {api_data.get('msg', '未知错误')}"
            if send_wechat_message(fail_message, province):
                fail_count += 1
            continue
            
        current_data = api_data["result"]
        print("✅ 成功获取油价数据")
        print("🏢 省份:", current_data["prov"])
        print("🕒 更新时间:", current_data["time"])
        
    except Exception as e:
        print(f"❌ 请求{province} API时发生错误: {str(e)}")
        # 发送失败通知
        fail_message = f"❌ {province}油价查询失败\n错误信息: {str(e)}"
        if send_wechat_message(fail_message, province):
            fail_count += 1
        continue

    # 尝试读取上次存储的油价数据
    print(f"\n[步骤2] 📚 读取{province}历史油价数据...")
    last_data = None
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r') as f:
                last_data = json.load(f)
            print(f"✅ 成功读取历史数据 (记录时间: {last_data.get('time', '未知')})")
        except Exception as e:
            print(f"❌ 读取历史数据文件失败: {str(e)}")
            last_data = None
    else:
        print("⚠️ 历史数据文件不存在，将创建新文件")

    # 准备各油品的涨跌信息
    print(f"\n[步骤3] 📈 计算{province}油价变化...")
    p0 = get_price_change(current_data, last_data, "p0", "0号柴油")
    p89 = get_price_change(current_data, last_data, "p89", "89号汽油")
    p92 = get_price_change(current_data, last_data, "p92", "92号汽油")
    p95 = get_price_change(current_data, last_data, "p95", "95号汽油")
    p98 = get_price_change(current_data, last_data, "p98", "98号汽油")

    # 格式化单个省份的消息
    province_message = f"""【⛽{province}油价】
🏢 省份: {current_data["prov"]}
🕒 更新时间: {current_data["time"]}

📊 当前价格 vs 历史价格:
⛽ 0号柴油: {p0['current_price']} {p0['emoji']}{p0['symbol']} (历史: {p0['last_price']} | 变化: {p0['change']})
⛽ 89号汽油: {p89['current_price']} {p89['emoji']}{p89['symbol']} (历史: {p89['last_price']} | 变化: {p89['change']})
⛽ 92号汽油: {p92['current_price']} {p92['emoji']}{p92['symbol']} (历史: {p92['last_price']} | 变化: {p92['change']})
⛽ 95号汽油: {p95['current_price']} {p95['emoji']}{p95['symbol']} (历史: {p95['last_price']} | 变化: {p95['change']})
⛽ 98号汽油: {p98['current_price']} {p98['emoji']}{p98['symbol']} (历史: {p98['last_price']} | 变化: {p98['change']})

📈 数据来源: 天行API"""
    
    # 保存当前油价数据
    print(f"\n[步骤4] 💾 保存{province}油价数据...")
    try:
        with open(DATA_FILE, 'w') as f:
            json.dump(current_data, f)
        print(f"✅ 数据已保存到 {DATA_FILE}")
    except Exception as e:
        print(f"❌ 保存数据失败: {str(e)}")

    # 立即发送该省份的通知
    print(f"\n[步骤5] 📤 发送{province}油价通知...")
    print("-"*50)
    print(province_message.strip())
    print("-"*50)
    
    if send_wechat_message(province_message, province):
        success_count += 1
    
    # 添加短暂延迟，避免推送过于频繁
    if len(PROVINCES) > 1:
        print("⏳ 等待2秒后处理下一个省份...")
        time.sleep(2)

# 发送汇总通知
print("\n[最终汇总] 📋")
summary_message = f"""✅ 油价查询完成
📊 统计结果:
✅ 成功: {success_count} 个省份
❌ 失败: {fail_count} 个省份
🎉 总计: {success_count + fail_count} 个省份"""

print(summary_message)

if success_count > 0 or fail_count > 0:
    send_wechat_message(summary_message, "汇总")

print("\n" + "="*50)
print("🎊 脚本执行完毕")
print("="*50)